<?php
namespace app\common\model;

use think\Model;
use think\Request;
use think\Session;

/**
 * 模板模型基类
 */
class FormworkBaseModel extends Model
{
    public static $fo_id;

    /**
     * 模型基类初始化
     */
    public static function init()
    {
        parent::init();
        // 后期静态绑定fo_id
        self::bindFoId(get_called_class());
    }

    /**
     * 后期静态绑定类名称
     * 用于定义全局查询范围的formwork_order_id条件
     * 子类调用方式:
     *   非静态方法:  self::$fo_id
     *   静态方法中:  $self = new static();   $self::$fo_id
     * @param $calledClass
     */
    private static function bindFoId($calledClass)
    {
        $class = [];
        if (preg_match('/app\\\(\w+)/', $calledClass, $class)) {
            $controller = str_replace($class[0] . '\\model\\','',$calledClass);
            $callfunc = 'set' . ucfirst($class[1]) . 'FoId';
            method_exists(new self, $callfunc) && self::$callfunc(strstr($controller, '\\',true));
        }
    }

    /**
     * 设置fo_id (store模块)
     */
    protected static function setStoreFoId($s_name='')
    {
        $session = Session::get('hema_'.$s_name);
        !empty($session) && self::$fo_id = $session['formwork_order_id'];
    }

    /**
     * 设置fo_id (api模块)
     */
    protected static function setApiFoId($s_name='')
    {
        $request = Request::instance();
        self::$fo_id = $request->param('fo_id');
    }
	
	/**
     * 设置fo_id (helper模块)
     */
    protected static function setHelperFoId($s_name='')
    {
        $request = Request::instance();
        self::$fo_id = $request->param('fo_id');
    }

    /**
     * 定义全局的查询范围
     */
    protected function base($query)
    {
        if (self::$fo_id > 0) {
            $query->where($query->getTable() . '.formwork_order_id', self::$fo_id);
        }
    }

}
